<template>
  <div>
    <el-card class="box-card">
      <el-button
        type="primary"
        size="default"
        icon="Plus"
        @click="addTrademark"
      >
        添加品牌
      </el-button>
      <el-table style="width: 100%; margin: 10px 0" border :data="trademarkArr">
        <el-table-column label="序号" width="180" align="center" type="index" />
        <!--      使用prop指定列显示内容对应的属性-->
        <el-table-column label="品牌名称" prop="tmName" />
        <!--      使用插槽替换列显示内容-->
        <el-table-column label="品牌Logo">
          <template v-slot:default="{ row }">
            <img :src="row.logoUrl" style="width: 100px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template v-slot:default="">
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateTrademark"
            ></el-button>
            <el-button type="primary" size="small" icon="Delete"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 7, 9]"
        :background="true"
        layout="prev, pager, next, jumper, ->, sizes, total"
        :total="total"
        :pager-count="9"
        @current-change="onPageChange"
        @size-change="onSizeChange"
      />
    </el-card>

    <el-dialog v-model="dialogFormVisible" title="添加品牌">
      <el-form label-position="right" label-width="80px" style="width: 80%">
        <el-form-item label="品牌名称">
          <el-input
            placeholder="请输入品牌名称"
            v-model="trademarkParams.tmName"
          ></el-input>
        </el-form-item>
        <!--        上传组件action中/api写死-->
        <el-form-item label="品牌LOGO">
          <el-upload
            class="avatar-uploader"
            :action="uploadAction"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :on-error="handleAvatarError"
          >
            <img
              v-if="trademarkParams.logoUrl"
              :src="trademarkParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button type="primary" @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="onConfirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import {
  reqAddOrUpdateTrademark,
  reqHasTrademark,
} from '@/api/product/trademark'
import { ElMessage, ElNotification, UploadProps } from 'element-plus'
import {
  ResponseData,
  Trademark,
  TrademarkRecords,
} from '@/api/product/trademark/type'

let pageNo = ref<number>(1)
let limit = ref<number>(3)
let total = ref<number>(0)
let trademarkArr = ref<TrademarkRecords>([])
let dialogFormVisible = ref(false)
// 上传API
let uploadAction = ref(
  `${import.meta.env.VITE_APP_BASE_API}/admin/product/fileUpload`,
)
let trademarkParams = reactive<Trademark>({
  tmName: '',
  logoUrl:
    'http://139.198.127.41:9000/sph/20230606/006cSBLKgy1fvgcykucvwj30j60j6q64.jpg',
})

const getHasTrademark = async () => {
  try {
    const ret = await reqHasTrademark(pageNo.value, limit.value)
    trademarkArr.value = ret.data.records
    total.value = ret.data.total
  } catch (e: Error) {
    ElNotification({
      type: 'error',
      message: e.message,
    })
  }
}

onMounted(async () => {
  await getHasTrademark()
})

const onPageChange = () => {
  getHasTrademark()
}
const onSizeChange = () => {
  // 每页条数变化可能导致分页数变化, 故回到第一页
  pageNo.value = 1
  getHasTrademark()
}

const addTrademark = () => {
  dialogFormVisible.value = true

  // 清空收集数据
  trademarkParams.tmName = ''
  trademarkParams.logoUrl = ''
}

const updateTrademark = () => {
  dialogFormVisible.value = true
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (
    rawFile.type !== 'image/jpeg' &&
    rawFile.type !== 'image/png' &&
    rawFile.type !== 'image/gif'
  ) {
    ElMessage.error('文件格式只能说JPG、PNG或GIF格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 4) {
    ElMessage.error('上传文件大小应小于4MB!')
    return false
  }
  return true
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response: ResponseData & { data: string },
) => {
  if (response.ok) {
    trademarkParams.logoUrl = response.data
    ElMessage.success('上传文件成功!')
  } else {
    trademarkParams.logoUrl = ''
    ElMessage.error(`上传文件失败: ${response.message}!`)
  }
}

const handleAvatarError = (error: Error) => {
  trademarkParams.logoUrl = ''
  ElMessage.error(`上传文件失败: ${error.message}!`)
}

const onConfirm = async () => {
  try {
    // 提交添加请求
    await reqAddOrUpdateTrademark(trademarkParams)
    // 提示信息
    ElMessage.success('添加品牌成功!')
    // 获取新的数据
    await getHasTrademark()
  } catch (e: Error) {
    ElMessage.error(`添加品牌失败: ${e.message}`)
  } finally {
    // 关闭对话框
    dialogFormVisible.value = false
  }
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
